<template>
    <div class="app-container">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                 label-width="68px">
            <el-form-item label="商品名称" prop="waresName">
                <el-input
                    v-model="queryParams.waresName"
                    placeholder="请输入商品名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="类目名称" prop="classifyName">
                <el-input
                    v-model="queryParams.classifyName"
                    placeholder="请输入类目名称"
                    clearable
                    @keyup.enter.native="handleQuery"
                />
            </el-form-item>
            <el-form-item label="开始时间" prop="startTime">
                <el-date-picker clearable
                                v-model="queryParams.startTime"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择兑换有效期开始时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="endTime">
                <el-date-picker clearable
                                v-model="queryParams.endTime"
                                type="date"
                                value-format="yyyy-MM-dd"
                                placeholder="请选择兑换有效期结束时间">
                </el-date-picker>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['mall:wares:add']"
                >新增
                </el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-edit"
                    size="mini"
                    :disabled="single"
                    @click="handleUpdate"
                    v-hasPermi="['mall:wares:edit']"
                >修改
                </el-button>
            </el-col>
            <el-col :span="1.5" style="display: none">
                <el-button
                    type="danger"
                    plain
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                    v-hasPermi="['mall:wares:remove']"
                >删除
                </el-button>
            </el-col>
            <el-col :span="1.5" style="display: none">
                <el-button
                    type="warning"
                    plain
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                    v-hasPermi="['mall:wares:export']"
                >导出
                </el-button>
            </el-col>
            <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table border v-loading="loading" :data="waresList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="ID" align="center" prop="waresId"/>
            <el-table-column label="商品名称" align="center" prop="waresName"/>
            <el-table-column label="兑换类型" align="center" prop="exchangeType">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.exchangeType==0">实物</el-tag>
                    <el-tag type="danger" v-if="scope.row.exchangeType==1">券码</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="兑换规格" align="center" prop="specName"/>
            <el-table-column label="所属类目" align="center" prop="classifyName">
                <template slot-scope="scope">
                    {{ scope.row.bizClassify.classifyName }}
                </template>
            </el-table-column>

            <el-table-column label="消耗积分数" align="center" prop="expendNum"/>
            <el-table-column label="库存数目" align="center" prop="stockNum"/>
            <el-table-column label="兑换开始时间" align="center" prop="startTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {hh}:{ii}:{ss}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="兑换结束时间" align="center" prop="endTime" width="180">
                <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {hh}:{ii}:{ss}') }}</span>
                </template>
            </el-table-column>
            <el-table-column label="上/下架" align="center">
                <template slot-scope="scope">
                    <el-switch
                        v-model="scope.row.status"
                        active-value="0"
                        inactive-value="1"
                        @change="handleStatusChange(scope.row)"
                    ></el-switch>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['mall:wares:edit']"
                    >修改
                    </el-button>
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['mall:wares:remove']"
                    >删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total>0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改商品列表对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="商品类目" prop="classifyId">
                    <el-select v-model="form.classifyId" placeholder="请选择商品发布类目">
                        <el-option
                            v-for="classify in classifyList"
                            :key="classify.classifyId"
                            :label="classify.classifyName"
                            :value="classify.classifyId"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品类型" prop="exchangeType">
                    <el-radio-group v-model="form.exchangeType">
                        <el-radio :key="type.label" :label="type.label" v-for="type in exchangeType">{{ type.name }}
                        </el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="商品图片" prop="imgUrl">
                    <el-col :span="6">
                        <el-image :src="form.imgUrl" :preview-src-list="srcList" v-if="form.imgUrl!=null"
                                  style="width:148px;height: 148px;"></el-image>
                    </el-col>
                    <el-col :span="2" style="padding-right:5px "></el-col>
                    <el-col :span="10">
                        <el-upload
                            :action="uploadFileUrl"
                            list-type="picture-card"
                            :limit="1"
                            :on-success="handleUploadSuccess"
                            :show-file-list="false"
                            :headers="headers"
                            class="upload-file-uploader"
                            ref="fileUpload"><i class="el-icon-plus"></i>
                        </el-upload>
                    </el-col>
                </el-form-item>
                <el-form-item label="商品名称" prop="waresName">
                    <el-col :span="20">
                        <el-input v-model="form.waresName" placeholder="请输入商品名称" size="small" maxlength="30"
                                  show-word-limit clearable/>
                    </el-col>
                </el-form-item>
                <el-form-item label="兑换规格" prop="specName">
                    <el-col :span="20">
                        <el-input v-model="form.specName" placeholder="请输入兑换规格,1件或一张" maxlength="10"
                                  size="small" show-word-limit clearable/>
                    </el-col>
                </el-form-item>
                <el-form-item label="消耗积分" prop="expendNum">
                    <el-col :span="20">
                        <el-input v-model="form.expendNum" placeholder="请输入兑换该商品所需消耗积分数" maxlength="10"
                                  size="small" show-word-limit clearable/>
                    </el-col>
                </el-form-item>
                <el-form-item label="库存数" prop="stockNum">
                    <el-col :span="20">
                        <el-input v-model="form.stockNum" placeholder="请输入库存数目" maxlength="10" size="small"
                                  show-word-limit clearable/>
                    </el-col>
                </el-form-item>
                <el-form-item label="兑换时间">
                    <el-date-picker
                        v-model="times"
                        type="datetimerange"
                        range-separator="至"
                        start-placeholder="兑换开始时间"
                        end-placeholder="兑换结束时间">
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="兑换地址" prop="exchangeAddress">
                    <el-input v-model="form.exchangeAddress" type="textarea" placeholder="请输入兑换地址"/>
                </el-form-item>
                <el-form-item label="商品简介" prop="waresDesc">
                    <el-input type="textarea" v-model="form.waresDesc" placeholder="请输入商品简介"/>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {listWares, getWares, delWares, addWares, updateWares, changeWaresStatus} from "@/api/mall/wares";
import {listClassify} from "@/api/mall/classify";
import {getToken} from "@/utils/auth";

export default {
    name: "Wares",
    data() {
        return {
            baseUrl: process.env.VUE_APP_BASE_API,
            uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
            headers: {
                Authorization: "Bearer " + getToken(),
            },
            srcList: [],
            fileList: [],
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 商品列表表格数据
            waresList: [],
            times: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                waresName: null,
                exchangeType: null,
                specName: null,
                classifyId: null,
                classifyName: null,
                expendNum: null,
                stockNum: null,
                startTime: null,
                endTime: null,
                status: null,
            },
            // 查询参数
            classifyParams: {
                pageNum: 1,
                pageSize: 100
            },
            classifyList: {},
            exchangeType: [{"name": "实物", "label": 0}, {"name": "券码", "label": 1}],
            // 表单参数
            form: {
                "exchangeType": 0,
                "classifyId": 0,
                "imgUrl": "",
            },
            // 表单校验
            rules: {
                waresName: [
                    {required: true, message: '请输入商品名称', trigger: 'blur'},
                ],
                classifyId: [{required: true, message: '请选择商品类目', trigger: 'change'}],
                expendNum: [{required: true, message: '请兑换商品需要消耗的积分', trigger: 'blur'}],
                stockNum: [{required: true, message: '请输入商品库存', trigger: 'blur'}],
                imgUrl: [{required: true, message: '请上传商品图片', trigger: 'blur'}],
                times: [{required: true, message: '请选择兑换的时间', trigger: 'blur'}]
            }
        };
    },
    created() {
        this.getList();
        this.classify();
    },
    methods: {
        /** 商品类目 **/
        classify() {
            listClassify(this.classifyParams).then(response => {
                this.classifyList = response.rows;
            });
        },
        /** 查询商品列表列表 */
        getList() {
            this.loading = true;
            listWares(this.queryParams).then(response => {
                this.waresList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 上传成功回调
        handleUploadSuccess(res, file) {
            if (res.code === 200) {
                this.form.imgUrl = res.url
                this.srcList.push(res.url)
            }
        },
        // 表单重置
        reset() {
            this.form = {
                waresId: null,
                waresName: null,
                exchangeType: null,
                specName: null,
                classifyId: null,
                classifyName: null,
                expendNum: null,
                stockNum: null,
                startTime: null,
                endTime: null,
                exchangeAddress: null,
                waresDesc: null,
                status: null,
                createBy: null,
                createTime: null,
                updateBy: null,
                updateTime: null,
                imgUrl: null
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.waresId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.form.exchangeType = 0;
            this.open = true;
            this.title = "添加兑换商品";
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset();
            const waresId = row.waresId || this.ids
            getWares(waresId).then(response => {
                this.form = response.data;
                this.open = true;
                this.title = "修改商品列表";
            });
        },
        /** 提交按钮 */
        submitForm() {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (this.form.waresId != null) {
                        updateWares(this.form).then(response => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        addWares(this.form).then(response => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const waresIds = row.waresId || this.ids;
            this.$modal.confirm('是否确认删除商品列表编号为"' + waresIds + '"的数据项？').then(function () {
                return delWares(waresIds);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('mall/wares/export', {
                ...this.queryParams
            }, `wares_${new Date().getTime()}.xlsx`)
        },
        // 角色状态修改
        handleStatusChange(row) {
            let text = row.status === "0" ? "上架" : "下架";
            this.$modal.confirm('确认要"' + text + row.waresName + '这个商品嘛？').then(function () {
                return changeWaresStatus(row.classifyId, row.status);
            }).then(() => {
                this.$modal.msgSuccess(text + "成功");
            }).catch(function () {
                row.status = row.status === "0" ? "1" : "0";
            });
        },
    }
};
</script>
